package com.jianyun.jyzs.utils;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.widget.NotificationUtils;
import com.jrmf360.rylib.common.util.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangshijun on 2018/10/15.
 */

public class UpDateAPKUtil {


    private OkHttpClient okHttpClient;
    private static UpDateAPKUtil upDateAPKUtil;
    private Context mContext;
    public static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private String filePath;
    private String apkFils;

    private UpDateAPKUtil() {

    }

    public static UpDateAPKUtil getInstance() {
        if (upDateAPKUtil == null) {
            upDateAPKUtil = new UpDateAPKUtil();

        }
        return upDateAPKUtil;
    }


    public void cretaDownTask(Context context, String url, String name) {
        this.mContext = context;
        okHttpClient = new OkHttpClient();
        apkFils = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
        filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + name;
        //检查版本是否大于M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) mContext,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_CALL_PHONE);
            } else {
                startDown(url, name);
                ToastUtil.showToast(mContext, "权限已申请");
            }
        } else {
            startDown(url, name);
        }
    }

    public void startDown(String url, String name) {
        final NotificationUtils utils = new NotificationUtils(mContext);
        utils.initBuilder("", "", 0);
        downloadAPK(url, name, apkFils, new OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Log.i("test", "下载成功");
                utils.cancelNotification();
                install();
                //ToastUtil.showToast(mContext, "下载成功！");
            }

            @Override
            public void onDownloading(int progress) {
                Log.i("test", "下载进度：" + progress);
                utils.sendNotification("", "", progress);
            }

            @Override
            public void onDownloadFailed() {
                Log.e("err", "下载失败");
                ToastUtil.showToast(mContext, "下载失败！");
                utils.cancelNotification();
            }
        });
    }

    /**
     * 下载文件明
     *
     * @param name        文件名
     * @param url         URL
     * @param saveDirPath 保存路径
     * @param listener
     */
    public void downloadAPK(final String url, final String name, final String saveDirPath, final OnDownloadListener listener) {
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onDownloadFailed();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048*1024];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String path = isExistDir(saveDirPath, name);
                Log.i("test", "路径：" + path);
                try {
                    int tmpe1=-1;
                    int tmpe2=-1;
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(path, name);
                    fos = new FileOutputStream(file);
                    Log.i("test", "文件路径：" + file.getAbsolutePath());
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        tmpe2=tmpe1;
                        int progress = (int) (sum * 1.0f / total * 100);
                        tmpe1=progress;
                        if (tmpe2!=tmpe1){
                            // 下载中
                            listener.onDownloading(progress);
                        }
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess();
                } catch (Exception e) {
                    listener.onDownloadFailed();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    private String isExistDir(String saveDir, String name) throws IOException {
        // 下载位置
        File downloadFile = new File(saveDir);
        if (downloadFile.exists()) {
            downloadFile.delete();
        }

        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }

        return downloadFile.getAbsolutePath();

    }


    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();
    }


    private void install() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        File file = new File(filePath);
        if (Build.VERSION.SDK_INT >= 24) {

            Uri apkUri = FileProvider.getUriForFile(mContext, "com.jianyun.jyzs.FileProvider", file);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            mContext.startActivity(install);

        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }

    }
}
